package top.z.template.parse.ast.expression;

import top.z.template.Context;
import top.z.template.Source;
import top.z.template.Template;
import top.z.template.parse.Ast.Expression;
import top.z.template.parse.CharacterStream;
import top.z.template.parse.Span;

import java.io.IOException;
import java.io.OutputStream;

/**
 * String, 用双引号括起来, 支持转义: \n, \r, \t, \" 和 \\
 */
public class StringLiteral extends Expression {

    private final String value;

    public StringLiteral(Span span) {
        super(span);
        String        text           = getSpan().getText();
        String        unescapedValue = text.substring(1, text.length() - 1);
        StringBuilder builder        = new StringBuilder();

        CharacterStream stream = new CharacterStream(new Source(span.getSource().getPath(), unescapedValue));
        while (stream.hasNext()) {
            if (stream.match("\\\\", true)) {
                builder.append('\\');
            } else if (stream.match("\\n", true)) {
                builder.append('\n');
            } else if (stream.match("\\r", true)) {
                builder.append('\r');
            } else if (stream.match("\\t", true)) {
                builder.append('\t');
            } else if (stream.match("\\\"", true)) {
                builder.append('"');
            } else {
                builder.append(stream.consume());
            }
        }
        value = builder.toString();
    }

    public String getValue() {
        return value;
    }

    @Override
    public Object evaluate(Template template, Context context, OutputStream out) throws IOException {
        return value;
    }

}
